<?php
/**
 * @version $Id: pm_paypal.php 21 2010-05-14 13:24:08Z vladzimirs $
 * @package UnoCart
 * @copyright Авторские права (C) 2009-2010 UnoCart team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
error_reporting(0);
defined('_VALID_MOS') or die('Restricted access');
class pm_paypal
{
    function showPaymentForm()
    {
        ob_start();

?>
      <script type="text/javascript">
	    function pm_paypal(){
		  $_('payment_form').submit();
		}
	  </script>
      <?php

        $return = ob_get_contents();
        ob_get_clean();
        return $return;
    }

    function checkPaymentInfo(&$params)
    {
        return 1;
    }

    function getParams()
    {
        global $pm_paypal;
        return $pm_paypal;
    }

    function showAdminFormParams($params)
    {
        $array_params = array('testmode', 'email_received', 'transaction_end_status',
            'transaction_pending_status', 'transaction_failed_status');
        foreach ($array_params as $key) {
            if (!isset($params[$key]))
                $params[$key] = '';
        }
        ob_start();

?>
       <table class = "unocart_border" width = "80%" align = "left">
         <tr>
           <td width = "30%" align = "right">
             <?php

        echo _UNOCART_PAYPAL_TESTMODE;
        echo mosToolTip(_UNOCART_PAYPAL_TESTMODE_DESCRIPTION);

?>
           </td>
           <td>
             <?php

        echo mosHTML::yesnoSelectList('pm_params[testmode]',
            'class = "inputbox" size = "1"', $params['testmode']);

?>
           </td>
         </tr>
         <tr>
           <td align = "right">
             <?php

        echo _UNOCART_PAYPAL_EMAIL;
        echo mosToolTip(_UNOCART_PAYPAL_EMAIL_DESCRIPTION);

?>
           </td>
           <td>
             <input type = "text" class = "inputbox" name = "pm_params[email_received]" value = "<?php

        echo $params['email_received']

?>" />
           </td>
         </tr>
         <tr>
           <td align = "right">
             <?php

        echo _UNOCART_PAYPAL_TRANSACTION_END;
        echo mosToolTip(_UNOCART_PAYPAL_TRANSACTION_END_DESCRIPTION);

?>
           </td>
           <td>
             <?php

        echo mosHTML::selectList(unocartOrderStatus::getAllOrders(),
            'pm_params[transaction_end_status]', 'class = "inputbox" size = "1"',
            'status_id', 'status_name', $params['transaction_end_status'])

?>
           </td>
         </tr>
         <tr>
           <td align = "right">
             <?php

        echo _UNOCART_PAYPAL_TRANSACTION_PENDING;
        echo mosToolTip(_UNOCART_PAYPAL_TRANSACTION_PENDING_DESCRIPTION);

?>
           </td>
           <td>
             <?php

        echo mosHTML::selectList(unocartOrderStatus::getAllOrders(),
            'pm_params[transaction_pending_status]', 'class = "inputbox" size = "1"',
            'status_id', 'status_name', $params['transaction_pending_status'])

?>
           </td>
         </tr>
         <tr>
           <td align = "right">
             <?php

        echo _UNOCART_PAYPAL_TRANSACTION_FAILED;
        echo mosToolTip(_UNOCART_PAYPAL_TRANSACTION_FAILED_DESCRIPTION);

?>
           </td>
           <td>
             <?php

        echo mosHTML::selectList(unocartOrderStatus::getAllOrders(),
            'pm_params[transaction_failed_status]', 'class = "inputbox" size = "1"',
            'status_id', 'status_name', $params['transaction_failed_status'])

?>
           </td>
         </tr>
       </table>
      <?php

        $return = ob_get_contents();
        ob_get_clean();
        return $return;
    }

    function checkTransaction(&$params, &$order)
    {
        $paypal = new payPaypal($params, $order);
        return $paypal->testPay($params, $order->order_number);
    }

    function showEndForm(&$params, $order_hash = null)
    {
        $parseString = new parseString($params);
        $paypal = new payPaypal($parseString->parseStringToParams());
        return $paypal->getForm(0, $_SESSION['currency_code'], $order_hash);
    }
}


/*
PAY PayPol Version 1.0
Victor Antonyak class
*/
class payPaypal
{
    var $host;
    var $url;
    var $email;
    var $return;
    var $cancel_return;
    var $order;
    function payPaypal($params, &$order)
    {
        // Z adminky tyagnuty cju zminnu
        if ($params['testmode']) {
            $this->host = "www.sandbox.paypal.com";
        } else {
            $this->host = "www.paypal.com";
        }
        $this->url = "/cgi-bin/webscr";
        $this->email = $params['email_received'];
        $this->notify_url = JPATH_SITE .
            "/index2.php?option=com_unocart&task=notify&no_html=1";
        $this->return = JPATH_SITE .
            "/index.php?option=com_unocart&task=checkout&step=7";
        $this->cancel_return = JPATH_SITE .
            "/index.php?option=com_unocart&task=checkout&step=6&error=1";
        $this->order = $order;
    }

    function getForm($tax = 0, $currency_code = 'EUR', $order_hash)
    {
        $s = '<form id="paypal_form" action="https://' . $this->host .
            '/cgi-bin/webscr" name = "paypal_form" method = "post">';
        $cart = new Cart();
        $i = 1;
        $summ = 0;
        foreach ($cart->products as $product) {
            $s .= '<input type = "hidden" name = "amount_' . $i . '" value = "' . $product['price'] .
                '" />';
            $s .= '<input type = "hidden" name = "item_name_' . $i . '" value = "' . $product['product_name'] .
                '" />';
            $s .= '<input type = "hidden" name = "quantity_' . $i++ . '" value = "' . $product['quantity'] .
                '" />';
            $summ += $product['price'] * $product['quantity'];
        }
        $s .= "<br /><br /><textarea class = 'inputbox' name = 'custom' id = 'order_add_info'></textarea>
			<input type='hidden' name='cmd' value='_cart'>
			<input type='hidden' name='business' value='" . $this->email . "'>
		    <input type='hidden' name='upload' value='1'>
			<input type='hidden' name='notify_url' value='" . $this->notify_url . "'>
			<input type='hidden' name='return' value='" . $this->return . "'>
			<input type='hidden' name='rm' value='2'>
			<input type='hidden' name='cancel_return' value='" . $this->cancel_return .
            "'>
			<input type='hidden' name='on0' value=''>
			<input type='hidden' name='on1' value=''>
			<input type='hidden' name='handling_cart' value='" . $_SESSION['unocart_price_shipping'] .
            "'>
			<input type='hidden' name='tax' value='" . $tax . "'>
			<input type='hidden' name='charset' value='utf-8'>
			<input type='hidden' name='no_shipping' value='1'>
			<input type='hidden' name='no_note' value='1'>
			<input type='hidden' name='custom' value='" . $order_hash . "'>
			<input type='hidden' name='currency_code' value='" . $currency_code .
            "'><br />
			<input class = 'button' type = 'button' name = 'finish_registration' value = '" .
            _UNOCART_ORDER_FINISH . "' onclick='deleteData()' />
			";
        $s .= "</form>\n";
        return $s;
    }

    function checkParameters($params)
    {
        if ($this->order->order_total != $_POST['mc_gross'] || $this->email != $_POST['business'] ||
            $this->order->currency_code != $_POST['mc_currency']) {
            return 0;
        } else {
            return 1;
        }
    }

    function testPay($params, $order_number)
    {
        $req = 'cmd=_notify-validate';
        if (!$this->checkParameters($params)) {
            return array(0, 'Bad data. Order number ' . $order_number);
        }

        foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }
        $payment_status = Jstring::trim(stripslashes($_POST['payment_status']));

        $header = '';
        // post back to PayPal system to validate
        $header .= "POST " . $this->url . " HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . Jstring::strlen($req) . "\r\n\r\n";

        $fp = fsockopen($this->host, 80, $errno, $errstr, 30);
        if (!$fp) {
            return array(0, 'Http error. Order number ' . $order_number);
        } else {
            @fputs($fp, $header . $req);
            while (!@feof($fp)) {
                $res = @fgets($fp, 1024);
            }
            fclose($fp);
            if (strcmp($res, "VERIFIED") == 0) {
                // check the payment_status is Completed
                // check that txn_id has not been previously processed
                // check that receiver_email is your Primary PayPal email
                // check that payment_amount/payment_currency are correct
                // process payment
                if ($payment_status == 'Completed') {
                    return array(1, '');
                } else
                    if ($payment_status == 'Pending') {
                        return array(-1, $pending_reason = Jstring::trim(stripslashes($_POST['pending_reason'])));
                    } else {
                        return array(0, "Order number $order_number.\nPaypal error\nPayment status - $payment_status.");
                    }

            } else
                if (strcmp($res, "INVALID") == 0) {
                    return array(0, 'Invalid response . Order number ' . $order_number);
                } else {
                    return array(0, 'Error connect with paypal. Order number ' . $order_number);
                }
        }
    }
}

?>